<?php

namespace Icsoc\UIBundle\Controller;

use Doctrine\ORM\NoResultException;
use Icsoc\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Icsoc\SecurityBundle\Entity\UserMenu;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

/**
 * Class MainController
 *
 * @package Icsoc\UIBundle\Controller
 */
class MainController extends BaseController
{
    const MENU_DIR = '/menu';

    /** 需要过滤的菜单 */
    const MENU_BUSNIESS_GROUP = 'icsoc_business_group_index';
    const MENU_BUSNIESS_GROUP_REPORT = 'icsoc_report_group_home';

    private $filterMenu = array(
        'group' => array(
            0 => self::MENU_BUSNIESS_GROUP,
            1 => self::MENU_BUSNIESS_GROUP_REPORT,
        ),
    );
    //所有用户都拥有以下权限 array(1,2,3)
    private $addMenuUrl = array(
        'icsoc_security_develop_download_work_index',
    );

    /**
     * @return Response
     */
    public function indexAction()
    {
        $vccId = $this->getVccId();
        $em = $this->getDoctrine()->getManager();
        $actionList = $this->getActionList();
        if ($actionList == 'all') {
            $isSetting = true;
        } else {
            $actionArr = explode(',', $actionList);
            $isSetting = in_array('icsoc_security_setting', $actionArr) ? true : false;
        }
        try {
            $res = $em->getRepository("IcsocSecurityBundle:CcCcods")->createQueryBuilder("c")->select('c.systemName')
                ->where("c.vccId = :vccId")->setParameter('vccId', $vccId)->getQuery()->getSingleResult();
        } catch (NoResultException $e) {
            $res = array();
        }
        $systemName = isset($res['systemName']) && !empty($res['systemName']) ?
            $res['systemName'] : $this->trans($this->container->getParameter('system_name'));

        return $this->render('IcsocUIBundle:Main:index.html.twig', array(
            'title' => $systemName,
            'isSetting' => $isSetting,
        ));
    }

    /**
     * @return Response
     */
    public function dashboardAction()
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();
        $userId = $user->getId();
        $vccId = $user->getVccId();
        $flag = $user->getLoginType();
//        $actionList = $user->getActionList();
//        $actions = explode(',', $actionList);
        $topNOtice = $em->getRepository("IcsocSecurityBundle:CcAnnouncement")->getNumNotcie(0, 3, 1); //获取ccod中的公告
        //先查看是否有查看公告的权限；
//        $allowSelctNotice = ($actionList == 'all'  || in_array('icsoc_notice_index', $actions)) ? true : false;
//        $notices = array();
//        if ($allowSelctNotice) {
        $notices = $em->getRepository("IcsocSecurityBundle:CcAnnouncement")->getNumNotcie($vccId, 7);
        //}
        /** @var \Icsoc\SecurityBundle\Entity\CcCcods $ccods */
        $ccods = $em->getRepository("IcsocSecurityBundle:CcCcods")->find($user->getVccId());
        $agent = array();
        $status = $this->container->getParameter('vcc_status');
        $feeType = $this->container->getParameter('feetype');
        $agent['status'] = $status[$ccods->getStatus()];
        $agent['if_out'] = $ccods->getIfOut() == 1 ? "启用 ￥".$ccods->getOutFlat()."/分钟" : "未启用";
        $agent['groups'] = $ccods->getGroups() == 0 ? "不限" : $ccods->getGroups();
        $agent['fee_type'] = isset($feeType[$ccods->getFeeType()]) ? $feeType[$ccods->getFeeType()] : '';
        $agent['vcc_code'] = $ccods->getVccCode();
        $agent['agent_logins'] = $ccods->getAgentLogins();
        $agent['agents'] = $ccods->getAgents();
        $agent['ivr_line'] = $ccods->getIvrLines();
        $agent['open_date'] = $ccods->getOpenDate()->format('Y-m-d');
        $agent['due_date'] = $ccods->getDueDate()->format('Y-m-d');
        $phones = $this->get('icsoc_data.model.phone')->getCcPhones($vccId);
        //cc_phone400s表不能生成实体；
        $agent['phone_total'] = $phones['total'];
        if ($agent['phone_total'] >= 2) {
            $agent['allstr'] = $phones['allstr'] ? $phones['allstr'] : '';
            $agent['fivestr'] = $phones['fivestr'] ? $phones['fivestr'] : '';
        } else {
            $agent['lasfive'] = $phones['las'] ? $phones['las'] : '';
        }
        $agent['que_total'] = $em->getRepository("IcsocSecurityBundle:WinQueue")->getQueCount($user->getVccId());
        $agent['agent_total'] = $em->getRepository("IcsocSecurityBundle:WinAgent")->getCountAgent($user->getVccId());
        $agent['login_type'] = $user->getLoginType();
        $userMenus = $em->getRepository("IcsocSecurityBundle:UserMenu")->getUserMenu($userId, $flag);
        $actionList = $user->getActionList();
        $actionArr = explode(',', $actionList);
        $validMenu = array();

        /** @var bool $isEnableGroup 是否启用业务组 */
        $isEnableGroup = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->isEnableGroup($user->getVccId());

        foreach ($userMenus as $menus) {
            if ($actionList != 'all' && !in_array($menus['menuUrl'], $actionArr)) {
                continue;
            }

            /** 未启用业务组过滤掉业务组相关功能 */
            if (empty($isEnableGroup) && in_array($menus['menuUrl'], $this->filterMenu['group'])) {
                continue;
            }

            try {
                $this->container->get('router')->generate($menus['menuUrl']);
                $validMenu[] = $menus;
            } catch (RouteNotFoundException $e) {
            }
        }
        $tree = $em->getRepository("IcsocMenuBundle:Menu")->getTree(0);
        $menuIds = array();
        foreach ($userMenus as $menu) {
            $menuIds[] = $menu['menuId'];
        }
        $menuList = $treeList = array();
        foreach ($tree as $val) {
            if ($this->get('icsoc_core.common.class')->isDisableMenu($val['id'], $vccId)) {
                $treeList[$val['id']] = $val;
            }
        }
        //所有用户都拥有以下权限
        foreach ($this->addMenuUrl as $val) {
            $actionArr[] = $val;
        }
        //96,98为帮助向导和参数设置的id;
        foreach ($treeList as $v) {
            if ($actionList != 'all' &&
                (!in_array($v['menu_url'], $actionArr) && !$v['has_children']) && !in_array($v['id'], array(96, 94))
            ) {
                continue;
            }

            /** 未启用业务组过滤掉业务组相关功能 */
            if (empty($isEnableGroup) && in_array($v['menu_url'], $this->filterMenu['group'])) {
                continue;
            }

            if (isset($treeList[$v['parent_id']])) {
                $treeList[$v['parent_id']]['son'][] = &$treeList[$v['id']];
            } else {
                $menuList[] = &$treeList[$v['id']];
            }
        }
        $res = $menuList;
        foreach ($menuList as $k => $item) {
            if ($item['has_children'] && isset($item['son'])) {
                foreach ($item['son'] as $s1 => $son1) {
                    if ($son1['has_children'] && isset($son1['son'])) {
                        foreach ($son1['son'] as $s2 => $son2) {
                            if (isset($son2['has_children']) && $son2['has_children'] == 1 && !isset($son2['son'])) {
                                unset($res[$k]['son'][$s1]['son'][$s2]);
                            }
                        }
                        if (empty($res[$k]['son'][$s1]['son'])) {
                            unset($res[$k]['son'][$s1]);
                        }
                    } elseif ($son1['has_children'] && (!isset($son1['son']) || empty($son1['son']))) {

                        unset($res[$k]['son'][$s1]);
                    }
                }
                if (empty($res[$k]['son'])) {
                    unset($res[$k]);
                }
            } elseif ($item['has_children'] && (!isset($item['son']) || empty($item['son']))) {
                unset($res[$k]);
            }
        }

        return $this->render("IcsocUIBundle:Main:dashboard.html.twig", array(
            'notices' => $notices,
            'agent' => $agent,
            'tags' => $validMenu,
            'menus' => $res,
            'topnotcies' => $topNOtice,
        ));
    }

    /**
     * 设置用户自定义菜单；
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function setUserMenuAction(Request $request)
    {
        $id = $request->get('id', 0);
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();
        $userId = $user->getId();
        $flag = $user->getLoginType();
        $userMenu = new UserMenu();
        if (empty($id)) {
            return new JsonResponse(array('error' => 1, 'message' => $this->trans('There is no menu')));
        } else {
            /** @var \Icsoc\MenuBundle\Entity\Menu $meun */
            $meun = $em->getRepository("IcsocMenuBundle:Menu")->find($id);
            if (empty($meun)) {
                return new JsonResponse(array('error' => 1, 'message' => $this->trans('There is no menu')));
            }
            //判断路由是否有异常
            try {
                $this->generateUrl($meun->getMenuUrl());
            } catch (RouteNotFoundException $e) {
                return new JsonResponse(array('error' => 1, 'message' => $this->trans('Failed to add')));
            }
        }
        //判断是否超过10个了
        $count = $em->getRepository("IcsocSecurityBundle:UserMenu")->getUserCountMenu($userId, $flag);
        if ($count >= 10) {
            return new JsonResponse(array('error' => 1, 'message' => $this->trans('The number of not more than 10')));
        }
        $userMenu->setMenuId($id);
        $userMenu->setUserId($userId);
        $userMenu->setUserFlag($flag);
        $em->persist($userMenu);
        $em->flush();
        $menuInfo = $em->getRepository("IcsocSecurityBundle:UserMenu")->getMenuInfo($userMenu->getId());
        $menuInfo['menuUrl'] = $this->generateUrl($menuInfo['menuUrl']);

        return new JsonResponse(array('error' => 0, 'data' => $menuInfo));
    }

    /**
     * 删除tag
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function delUserMenuAction(Request $request)
    {
        $id = $request->get('id', 0);
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();
        $userId = $user->getId();
        $flag = $user->getLoginType();
        $res = $em->getRepository("IcsocSecurityBundle:UserMenu")->deleteMenu($id, $userId, $flag);
        if ($res) {
            return new JsonResponse(array('error' => 0));
        }

        return new JsonResponse(array('error' => 1, 'message' => $this->trans('Delete fail')));
    }

    /**
     * 页面跳转信息信息
     *
     * @param Request $request
     *
     * @return Response
     */
    public function messageAction(Request $request)
    {
        $data = $request->get('data');
        if (!isset($data['link']) || count($data['link']) == 0) {
            $data['link'] = array(
                array('text' => '返回', 'href' => 'javascript:history.go(-1)'),
            );
        }
        if (!isset($data['type'])) {
            $data['type'] = 'info';
        }
        $data['default_url'] = $data['link'][0]['href'];
        $data['auto_redirect'] = isset($data['auto_redirect']) ? $data['auto_redirect'] : true;

        return $this->render(
            'IcsocUIBundle:Main:message.html.twig',
            array(
                'datavalue' => $data,
            )
        );
    }

    /**
     * 下载帮助文档;
     *
     * @param Request $request
     *
     * @return Response|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function downHelpAction(Request $request)
    {
        $id = $request->get('id', 0);
        $menu = $this->getDoctrine()->getRepository("IcsocMenuBundle:Menu")->find($id);
        if ($menu) {
//            $file = $menu->getAbsolutePath();
//            if (file_exists($file)) {
//                $response = new BinaryFileResponse($file);
//                $response->setContentDisposition('attachment', $menu->getHelpUrl());
            $flySys = $this->get("icsoc_filesystem");
            $filePath = $menu->getHelpUrl();
            try {
                $content = $flySys->read($filePath);

                return new Response($content, 200, array(
                    'Pragma' => 'Public',
                    'Expires' => 0,
                    'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
                    'Content-Length' => $flySys->getSize($filePath),
                    'Content-Transfer-Encoding' => 'binary',
                    'Accept-Ranges' => 'bytes',
                    'Content-Disposition' => 'attachment;filename='.basename($menu->getHelpUrl()),
                ));
            } catch (\Exception $e) {
                $this->get('logger')->warning($e->getMessage());
            }
            /* if ($flySys->has($filePath)) {
                 $content = $flySys->read($filePath);
                 return new Response($content, 200, array(
                     'Pragma' => 'Public',
                     'Expires' => 0,
                     'Cache-Component' => 'must-revalidate, post-check=0, pre-check=0',
                     'Content-Length' => $flySys->getSize($filePath),
                     'Content-Transfer-Encoding' => 'binary',
                     'Accept-Ranges' => 'bytes',
                     'Content-Disposition' => 'attachment;filename='.basename($menu->getHelpUrl())
                 ));
             }*/
        }
        $data = array(
            'data' => array(
                'msg_detail' => '对不起,该文档还没有整理',
                'type' => 'danger',
            ),
        );

        return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
    }

    /**
     * @param Request $request
     *
     * @return Response
     */
    public function setLangAction(Request $request)
    {
        $lan = $request->get('lan', 'zh-CN');
        $request->getSession()->set('_locale', $lan);

        return new Response();
    }
}
